<?php
/**
 * Author:   tangxiaowen
 * Email:    846506584@qq.com
 * Date:     2019/6/5 0005
 * Describe: 新颜征信类.
 */

namespace app\api\controller\xinyan;

use think\Controller;
use think\Request;
use think\Log;

class Xinyan extends Controller
{
    public function __construct()
    {
        parent::__construct();

        //日志初始化保存地址
        $setPath = strtolower(request()->module().'/'.request()->controller().'/'.request()->action().'/');
        Log::init(['path' => LOG_PATH.$setPath, 'type' => 'file']);
    }

    /**
     * 获取运营商信息.
     *
     * @param int $userId 用户ID
     */
    public function getOperator()
    {
        $header = Request::instance()->header();
        $userInfo = db('mem_info')->field('Mobile,TrueName,IDCard')->where('ID', $header['userid'])->find();
        if (!$userInfo) {
            returnErrorResult('用户信息不存在');
        }
        //写入对接产品记录表
        (new \app\common\controller\system\Docking())->addDocking(3, 2, 'xinyan', '获取用户新颜-运营商数据及报告');

        $system = model('System')->getSystemInfo();

        $xinyanConfig = $this->getXinyanConfig();
        $timeMark = date('YmdHis');
        $apiName = 'carrier'; //数据源英文名，可在对接文档附录查看apiname列表 （carrier 既 运营商授权）
        $TaskID = date('YmdHis').getRand(18);
        $jumpUrl = ''; //跳转地址 http://xjdd.huakodai.cn/index.php/app/authen
        $dataNotifyUrl = $system['SystemDomain'].'/api.php/xinyan/Callback/addOperator'; //原始数据回调地址
        $reportNotifyUrl = $system['SystemDomain'].'/api.php/xinyan/Callback/addOperatorReport'; //报告数据回调地址
        $apiEnc = md5($xinyanConfig['apiUser'].$timeMark.$apiName.$TaskID.$xinyanConfig['apiKey']);
        $url = "https://qz.xinyan.com/h5/{$xinyanConfig['apiUser']}/{$apiEnc}/{$timeMark}/{$apiName}/{$TaskID}?jumpUrl={$jumpUrl}&dataNotifyUrl={$dataNotifyUrl}&reportNotifyUrl={$reportNotifyUrl}&name={$userInfo['TrueName']}&idCardNum={$userInfo['IDCard']}&phone={$userInfo['Mobile']}";
        returnSuccessResult(['url' => $url]);
    }

    /**
     * 获取新颜配置参数 ua key.
     *
     * @return array
     */
    public function getXinyanConfig()
    {
        $data = db('sys_integrate')->alias('i')
            ->join('xb_sys_inteparameter in', 'i.ID = in.IntegrateID')
            ->where(['i.Status' => 1, 'i.EName' => 'xinyan'])
            ->select();

        if (!$data) {
            returnErrorResult('未配置新颜');
        }

        $temp = [];
        foreach ($data as $k => $v) {
            $temp[$v['ParaName']] = $v['ParaValue'];
        }

        if (!$temp || !isset($temp['apiUser']) || empty($temp['apiUser'])) {
            returnErrorResult('未配置新颜 apiUser');
        } elseif (!$temp || !isset($temp['apiKey']) || empty($temp['apiKey'])) {
            returnErrorResult('未配置新颜 apiKey');
        }

        return $temp;
    }
}
